import 'package:PollOnLine/utils/toast_utils.dart';
import 'package:dio/dio.dart' as dio;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:signature/signature.dart';

import '../../../bean/FileRes.dart';
import '../../../bean/request/SaveTaskFile.dart';
import '../../../network/network.dart';
import '../../../utils/utils.dart';
import 'signature_state.dart';

class SignatureLogic extends GetxController {
  final SignaturesState state = SignaturesState();

  // 签名
  late SignatureController controller = SignatureController(
    penStrokeWidth: 5,
    penColor: Colors.black,
    exportBackgroundColor: Colors.white,
  );

  late String writeId; // 问卷ID

  @override
  void onInit() {
    super.onInit();
    if (!isPad(Get.context!)) {
      // 强制横屏
      setScreenLandscape(true);
    }

    writeId = Get.arguments;
  }

  @override
  void onReady() {
    super.onReady();
  }

  Future<void> goBack() async {
    final Uint8List? data = await controller.toPngBytes();
    if (data == null) {
      toast.show("获取图片失败");
      return;
    }
    Get.back(result: data);
  }

  // 单文件上传
  Future<void> uploadFile() async {
    final Uint8List? data = await controller.toPngBytes();
    if (data == null) {
      return toast.show("获取图片失败");
    }
    // File file = File('${await PathProviderUtils().getTempDir()}/签名_$writeId.png');
    // file.writeAsBytesSync(data.buffer.asInt8List());
    // String fileName = PathUtils.getName(file.path);
    // late dio.MultipartFile multipartFile = dio.MultipartFile.fromFileSync(file.path, filename: fileName);
    late dio.MultipartFile multipartFile = dio.MultipartFile.fromBytes(data, filename: '签名_$writeId.png');
    ResultData resultData = await Api.uploadFile(multipartFile);
    if (resultData.isSuccess) {
      FileRes fileRes = FileRes.fromJson(resultData.data['data']);
      saveTaskFile(fileRes);
    }
  }

  // 保存任务文件信息
  Future<void> saveTaskFile(FileRes fileRes) async {
    SaveTaskFile saveTaskFile = SaveTaskFile();
    saveTaskFile.busType = BUS_TYPE_SIGNATURE;
    List<FileRes> list = [fileRes];
    saveTaskFile.fileShowList = list;
    saveTaskFile.writeId = writeId;

    ResultData resultData = await Api.saveTaskFile(saveTaskFile.toJson());
    if (resultData.isSuccess) {
      // 返回上个页面
      toast.show("上传成功");
      goBack();
    }
  }

  @override
  void onClose() {
    if (!isPad(Get.context!)) {
      // 强制竖屏
      setScreenLandscape(false);
    }
    super.onClose();
  }
}
